package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbActive;
import com.bwie.service.TbActiveService;
import com.bwie.mapper.TbActiveMapper;
import com.bwie.utils.R;
import com.bwie.utils.TokenUtils;
import com.bwie.vo.PageInfoVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
* @author 牛y
* @description 针对表【tb_active(抽奖活动表)】的数据库操作Service实现
* @createDate 2025-07-28 19:09:43
*/
@Service
public class TbActiveServiceImpl extends ServiceImpl<TbActiveMapper, TbActive>
    implements TbActiveService{

    @Autowired
    TbActiveMapper tbActiveMapper;

    @Autowired
    HttpServletRequest request;

    @Override
    public R getActiveList(PageInfoVo pageInfoVo) {
        Page<TbActive> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        Page<TbActive> activePage=tbActiveMapper.getActiveList(page,pageInfoVo);
        return R.OK(activePage);
    }

    @Override
    public R addActive(TbActive tbActive) {
        //获取token
        String token = request.getHeader("token");
        String userName = TokenUtils.getUserName(token);
        //名称校验
        TbActive active = tbActiveMapper.selectOne(new QueryWrapper<TbActive>().lambda().eq(TbActive::getActiveName, tbActive.getActiveName()));
        if(ObjectUtils.isNotEmpty(active)){
            return R.ERROR(500,"活动名称已存在，请换一手");
        }
        tbActive.setCreateBy(userName);
        tbActive.setCreateTime(new Date());
        tbActiveMapper.insert(tbActive);
        return R.OK();
    }

    @Override
    public R deleteById(Integer activeId) {
        TbActive active = tbActiveMapper.selectById(activeId);
        if(ObjectUtils.isEmpty(active)){
            return R.ERROR(500,"活动为空");
        }
        tbActiveMapper.deleteById(activeId);
        return R.OK();
    }

    @Override
    public R updateActive(TbActive tbActive) {
        TbActive active = tbActiveMapper.selectOne(new QueryWrapper<TbActive>().lambda().eq(TbActive::getActiveId, tbActive.getActiveId()));
        if(ObjectUtils.isEmpty(active)){
            return R.ERROR(500,"活动不存在");
        }
        tbActiveMapper.updateById(tbActive);
        return R.OK();
    }
}




